package cn.iocoder.boot.demokeycloakbk;

import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
public class ExampleController {

    @GetMapping("/public")
    public String publicEndpoint() {
        return "Public API success";
    }

    @GetMapping("/secured")
    public String securedEndpoint() {
        return "Secured API success";
    }

    @GetMapping("/products")
    @PreAuthorize("hasRole('backend-service')")
    public List<Product> products(Authentication authentication) {
        // 确保Authentication是KeycloakAuthenticationToken的实例
        if (authentication instanceof KeycloakAuthenticationToken) {
            KeycloakAuthenticationToken keycloakAuth = (KeycloakAuthenticationToken) authentication;
            // 获取用户角色
            Set<String> roles = keycloakAuth.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
            // 打印角色到控制台
            System.out.println("User Roles: " + roles);
        }


        ArrayList<Product> products = new ArrayList<>();
        products.add(new Product("111"));
        products.add(new Product("22"));
        products.add(new Product("333"));
        return products;
    }
}
